<template>
  <div class="app-container">
    <el-form :inline="true">
      <el-form-item label="部门名称">
        <el-input
          v-model="queryParams.deptName"
          placeholder="请输入部门名称"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="状态">
        <el-select v-model="queryParams.status" placeholder="部门状态" clearable size="small">
          <el-option
            v-for="dict in statusOptions"
            :key="dict.dictValue"
            :label="dict.dictLabel"
            :value="dict.dictValue"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button
          class="filter-item"
          type="primary"
          icon="el-icon-search"
          size="mini"
          @click="handleQuery"
        >搜索</el-button>
        <el-button
          class="filter-item"
          type="primary"
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['system:dept:add']"
        >新增</el-button>
      </el-form-item>
    </el-form>

    <el-table
      v-loading="loading"
      :data="deptList"
      row-key="deptId"
      default-expand-all
      :tree-props="{children: 'children', hasChildren: 'hasChildren'}"
    >
      <el-table-column prop="deptName" label="水站名称"></el-table-column>
      <el-table-column prop="leader" label="负责人" ></el-table-column>
      <el-table-column prop="phone" label="电话"></el-table-column>
      <!--<el-table-column prop="orderNum" label="排序" width="200"></el-table-column>-->
      <el-table-column prop="status" label="状态" :formatter="statusFormat" ></el-table-column>
      <el-table-column label="创建时间" align="center" prop="createTime" >
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['system:dept:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-plus"
            @click="handleAdd(scope.row)"
            v-hasPermi="['system:dept:add']"
          >新增</el-button>
          <el-button
            v-if="scope.row.parentId != 0"
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:dept:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-dialog :visible.sync="dialogVisible">
      <img width="100%" :src="dialogImageUrl" alt="">
    </el-dialog>

    <!-- 添加或修改部门对话框 -->
    <el-dialog :title="title" :visible.sync="open"   top="15px" width="50%"  >
      <el-form ref="form" :model="form" :rules="rules" label-width="80px" :inline="true" >
            <el-form-item label="上级部门" prop="parentId" v-if="form.parentId !== 0">
              <treeselect v-model="form.parentId" :options="deptOptions" placeholder="选择上级部门" />
            </el-form-item>

          <el-col :span="12">
            <el-form-item label="水站名称" prop="deptName">
              <el-input v-model="form.deptName" placeholder="请输入水站名称" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="负责人" prop="leader">
              <el-input v-model="form.leader" placeholder="请输入负责人" />
            </el-form-item>
          </el-col>

            <el-form-item label="手机号码" prop="phone"  >
              <el-input v-model="form.phone" placeholder="请输入手机号码" style="width: 400px;" />
            </el-form-item>



            <el-form-item label="选择省市区" prop="province"  label-width="100px" >
            <el-form-item>
              <el-select v-model="form.province" @change = "changeProvince" placeholder="请选择省份">
                <el-option
                  v-for="item in options"
                  :key="item.areaId"
                  :label="item.name"
                  :value="item.areaId">
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-select v-model="form.city"  @change = "changeCity" placeholder="请选择城市" >
                <el-option
                  v-for="item in cityOptions"
                  :key="item.areaId"
                  :label="item.name"
                  :value="item.areaId">
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-select v-model="form.district "   placeholder="请选择区/县">
                <el-option
                  v-for="item in area0ptions"
                  :key="item.areaId"
                  :label="item.name"
                  :value="item.areaId">
                </el-option>
              </el-select>
            </el-form-item>

          </el-form-item>


            <el-form-item label="详细地址" prop="address"  >
              <div style="width: 650px">
                <el-autocomplete
                  v-model="form.address"
                  :fetch-suggestions="querySearch"
                  placeholder="请输入详细地址"
                  style="width: 100%"
                  :trigger-on-focus="false"
                  @select="handleSelect"
                />
                <div style="margin: 5px">
                  <baidu-map class="map" :center="form.mapCenter"  v-if="hackReset" :zoom="mapZoom" :scroll-wheel-zoom="true"  @ready="handlerBMap" />
                </div>
              </div>
            </el-form-item>

          <!--<el-col :span="12">-->
            <!--<el-form-item label="显示排序" prop="orderNum">-->
              <!--<el-input-number v-model="form.orderNum"  :min="1" :max="200" ></el-input-number>-->
            <!--</el-form-item>-->
          <!--</el-col>-->
          <el-col :span="12">
            <el-form-item label="水站状态">
              <el-radio-group v-model="form.status">
                <el-radio
                  v-for="dict in statusOptions"
                  :key="dict.dictValue"
                  :label="dict.dictValue"
                >{{dict.dictLabel}}</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<style>
  .map {
    width: 100%;
    height: 400px;
  }
</style>
<script>
import { listDept, getDept, listAttr,initCategory,treeselect, delDept, addDept, updateDept, queryCityList } from "@/api/system/dept";
import { getToken } from '@/utils/auth'
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";

export default {
  components: { Treeselect },
  data() {
    return {
      city:{
        level:1,
        areaId : undefined
      },

      cityName:undefined,
      //省市区
      options:[],
      cityOptions:[],
      area0ptions:[],
      // 遮罩层
      loading: true,
      // 表格树数据
      deptList: [],
      // 部门部门树选项
      deptOptions: undefined,
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 状态数据字典
      statusOptions: [],
      // 查询参数
      queryParams: {
        deptName: undefined,
        status: undefined
      },
      // 表单参数
      form: {
        mapCenter: { lng: 0, lat: 0 },
        fileList: [{name: 'food.jpeg', url: 'https://fuss10.elemecdn.com/3/63/4e7f3a15429bfda99bce42a18cdd1jpeg.jpeg?imageMogr2/thumbnail/360x360/format/webp/quality/100'}, {name: 'food2.jpeg', url: 'https://fuss10.elemecdn.com/3/63/4e7f3a15429bfda99bce42a18cdd1jpeg.jpeg?imageMogr2/thumbnail/360x360/format/webp/quality/100'}]
      },
      // 表单校验
      rules: {
        parentId: [
          { required: true, message: "上级部门不能为空", trigger: "blur" }
        ],
        deptName: [
          { required: true, message: "部门名称不能为空", trigger: "blur" }
        ],
        orderNum: [
          { required: true, message: "菜单顺序不能为空", trigger: "blur" }
        ]
      },
      uploadImgUrl: process.env.VUE_APP_BASE_API + "/common/upload", // 上传的图片服务器地址
      headers: {
        Authorization: 'Bearer ' + getToken()
      },
      dialogImageUrl: '',
      dialogVisible: false,
      disabled: false,
      hackReset:false,
      mapZoom: 15,
    };
  },
  created() {
    this.getList();
    this.getCity();
    this.getDicts("sys_normal_disable").then(response => {
      this.statusOptions = response.data;
    });
  },
  methods: {
    search(){

    },
    getCity(){
      this.city.level =1
      this.city.areaId = undefined
      queryCityList(this.city).then(response=>{
        this.options = response.data

      })
    },
    changeProvince(event){
      console.log(this.form.province)
      this.city.areaId = event
      this.city.level =2
      queryCityList(this.city).then(response => {
        this.cityOptions = response.data
        this.queryParams.city = undefined
        this.queryParams.district =undefined
        this.form.city = undefined
        this.form.district =undefined

      })
    },
    changeCity(event){

      for (var i =0;i< this.cityOptions.length;i++)
        if (event == this.cityOptions[i].areaId){
          this.cityName = this.cityOptions[i].name
         this.querySearch1(this.cityName)
        }

      this.city.areaId = event
      this.city.level =3
      queryCityList(this.city).then(response => {
        this.area0ptions = response.data

        this.form.district =undefined
      })
    },
    handlerBMap({ BMap, map }) {
      this.BMap = BMap
      this.map = map
      let _this=this;
      if (_this.form.lng && _this.form.lat) {
        _this.form.mapCenter.lng = _this.form.lng
        _this.form.mapCenter.lat = _this.form.lat
        _this.mapZoom = 15
        // map.addOverlay(new _this.BMap.Marker(_this.form.mapCenter))
        _this.map.clearOverlays()
        _this.map.addOverlay(new _this.BMap.Marker(_this.form.mapCenter))
      } else {
        var geolocation=new BMap.Geolocation();
        geolocation.getCurrentPosition(function (r) {
          _this.form.mapCenter.lng = r.longitude;
          _this.form.mapCenter.lat = r.latitude
        })
        _this.mapZoom = 10
      }
    },
    querySearch1(queryString) {

      var that = this
      var myGeo = new this.BMap.Geocoder()
      myGeo.getPoint(queryString, function(point) {
        if (point) {
          that.form.mapCenter = point
          that.makerCenter(point)
        } else {
          that.form.mapCenter = null
        }
      }, this.locationCity)
      var options = {
        onSearchComplete: function(results) {
          if (local.getStatus() === 0) {
            // 判断状态是否正确
            var s = []
            for (var i = 0; i < results.getCurrentNumPois(); i++) {
              var x = results.getPoi(i)
              var item = { value: x.address + x.title, point: x.point }
              s.push(item)

            }
          }
        }
      }
      var local = new this.BMap.LocalSearch(this.map, options)
      local.search(queryString)
    },
    querySearch(queryString, cb) {

      var that = this
      var myGeo = new this.BMap.Geocoder()
      myGeo.getPoint(queryString, function(point) {
        if (point) {
          that.form.mapCenter = point
          that.makerCenter(point)
        } else {
          that.form.mapCenter = null
        }
      }, this.locationCity)
      var options = {
        onSearchComplete: function(results) {
          if (local.getStatus() === 0) {
            // 判断状态是否正确
            var s = []
            for (var i = 0; i < results.getCurrentNumPois(); i++) {
              var x = results.getPoi(i)
              var item = { value: x.address + x.title, point: x.point }
              s.push(item)
              cb(s)
            }
          } else {
            cb()
          }
        }
      }
      var local = new this.BMap.LocalSearch(this.map, options)
      local.search(queryString)
    },
    handleSelect(item) {
      var { point } = item
      this.form.mapCenter = point
      let geocoder= new BMap.Geocoder();  //创建地址解析器的实例
      geocoder.getLocation(point,rs=>{
        this.form.lng=point.lng;
        this.form.lat=point.lat;
        this.form.province=rs.addressComponents.province;
        this.form.city=rs.addressComponents.city;
        this.form.district=rs.addressComponents.district;
        this.form.street=rs.addressComponents.street;
      });
      this.makerCenter(point)
    },
    makerCenter(point) {
      if (this.map) {
        this.map.clearOverlays()
        this.map.addOverlay(new this.BMap.Marker(point))
        this.form.mapCenter.lng = point.lng
        this.form.mapCenter.lat = point.lat
        this.mapZoom = 15
      }
    },
    /** 查询部门列表 */
    getList() {
      this.loading = true;
      listDept(this.queryParams).then(response => {
        this.deptList = response.data;
        this.loading = false;
      });
    },
    /** 查询部门下拉树结构 */
    getTreeselect() {
      treeselect().then(response => {
        this.deptOptions = response.data;
      });
    },
    // 字典状态字典翻译
    statusFormat(row, column) {
      return this.selectDictLabel(this.statusOptions, row.status);
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        leader: undefined,
        lng:undefined,
        lat:undefined,
        province:undefined,
        city:undefined,
        district:undefined,
        street:undefined,
        deptId: undefined,
        parentId: 100,
        deptName: undefined,

        status: "0",
        mapCenter: { lng: 0, lat: 0 },
      };
      this.resetForm("form");
    },
    // tableRowClassName(row, index) {
    //   if (index === 1) {
    //     return 'info-row'
    //   } else if (index === 3) {
    //     return 'positive-row'
    //   }
    //   return ''
    // },
    /** 搜索按钮操作 */
    handleQuery() {
      this.getList();
    },
    /** 新增按钮操作 */
    handleAdd(row) {
      this.reset();
      this.hackReset = false
      this.$nextTick(() => {
        this.hackReset = true
      })
      this.getTreeselect();
      if (row != undefined) {
        this.form.parentId = row.deptId;
      }
      this.cityName =undefined
      this.open = true;
      this.title = "添加部门";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      this.getTreeselect();
      getDept(row.deptId).then(response => {

        this.form = response.data;
        this.form.province = Number(this.form.province)
        this.form.city = Number(this.form.city)
        this.form. district = Number(this.form.district)
        this.form.mapCenter={ lng:this.form.lng, lat: this.form.lat};
        this.cityName =undefined
        this.hackReset = false;
        this.city.level = 1;
        this.city.areaId = undefined
        queryCityList(this.city).then(response => {

          this.options= response.data
          this.city.areaId =this.form.province;
          this.city.level =2;
          queryCityList(this.city).then(response => {
            this.cityOptions = response.data
            this.city.areaId = this.form.city
            this.city.level =3
            queryCityList(this.city).then(response => {
              this.area0ptions = response.data

            })
          })
        })




        this.$nextTick(() => {
          this.hackReset = true
        })
        this.open = true;
        this.title = "修改部门";
      });
    },
    /** 提交按钮 */
    submitForm: function() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.deptId != undefined) {
            updateDept(this.form).then(response => {
              if (response.code === 200) {
                this.msgSuccess("修改成功");
                this.open = false;
                this.getList();
              } else {
                this.msgError(response.msg);
              }
            });
          } else {
            addDept(this.form).then(response => {
              if (response.code === 200) {
                this.msgSuccess("新增成功");
                this.open = false;
                this.getList();
              } else {
                this.msgError(response.msg);
              }
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      this.$confirm('是否确认删除名称为"' + row.deptName + '"的数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return delDept(row.deptId);
        }).then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        }).catch(function() {});
    }
  }
};
</script>
